// react/src/ReactLazy

// 想起了 Promise
const Uninitialized = -1;
const Pending = 0;
const Resolved = 1;
const Rejected = 2;

export const REACT_LAZY_TYPE = Symbol.for('react.lazy');

// React.lazy(() => import('./optimization/components/RenderDemo'));
export function lazy(ctor: any) {
  const payload = {
    _status: Uninitialized, // 初始值
    _result: ctor,
  };
  const lazyType = {
    // 还是注意 这里的是type的$$typeof 不是react元素的
    $$typeof: REACT_LAZY_TYPE,
    _payload: payload,
    _init: lazyInitializer,
  };
  return lazyType;
}

function lazyInitializer(payload: any) {
  if (payload._status === Uninitialized) {
    // () => import('./optimization/components/RenderDemo')
    const ctor = payload._result;
    const thenable = ctor(); // 执行函数
    // 必须是一个promise
    thenable.then(
      (moduleObject: any) => {
        if (payload._status === Pending || payload._status === Uninitialized) {
          // Transition to the next state.
          const resolved = payload;
          resolved._status = Resolved; // 完成了
          // 必须是一个 export default xx的组件 用来渲染的
          resolved._result = moduleObject; // 结果 加载完成了 就是我们的组件
        }
      },
      (error: any) => {
        // 发生了错误 错误边界？？？？
        if (payload._status === Pending || payload._status === Uninitialized) {
          // Transition to the next state.
          const rejected = payload;
          rejected._status = Rejected;
          rejected._result = error;
        }
      },
    );
    if (payload._status === Uninitialized) {
      // In case, we're still uninitialized, then we're waiting for the thenable
      // to resolve. Set it as pending in the meantime.
      const pending = payload;
      pending._status = Pending; // pending状态
      pending._result = thenable;
    }
  }
  if (payload._status === Resolved) {
  } else {
    // throw promise 渲染终止了 抛出错误
    throw payload._result;
  }
}

// 在beginWork中
function mountLazyComponent() {
  // const init = lazyComponent._init;
  // 执行了这个 init方法
  // let Component = init(payload);
}
